const { Chapter, Lecture } = require('../models');
const { validationResult } = require('express-validator');
const logger = require('../utils/logger');

class LectureController {
  // 获取所有章节及其讲义
  static async getAllChaptersWithLectures(req, res) {
    try {
      const chapters = await Chapter.getAllWithLectures();
      
      // 转换为前端需要的格式
      const formattedChapters = chapters.map(chapter => ({
        id: chapter.id,
        title: chapter.title,
        sort_order: chapter.sort_order,
        status: chapter.status,
        lectures: chapter.lectures.map(lecture => ({
          id: lecture.id,
          name: lecture.name,
          title: lecture.title,
          path: lecture.path,
          file_path: lecture.path, // 添加 file_path 字段供前端使用
          file_type: lecture.file_type,
          file_size: lecture.file_size
        }))
      }));

      res.json({
        success: true,
        data: formattedChapters,
        message: '获取章节和讲义列表成功'
      });
    } catch (error) {
      logger.error('获取章节和讲义列表失败:', error);
      res.status(500).json({
        success: false,
        message: '获取章节和讲义列表失败',
        error: error.message
      });
    }
  }

  // 获取特定章节及其讲义
  static async getChapterWithLectures(req, res) {
    try {
      const { chapterId } = req.params;
      const chapter = await Chapter.getByIdWithLectures(chapterId);
      
      if (!chapter) {
        return res.status(404).json({
          success: false,
          message: '章节不存在'
        });
      }

      const formattedChapter = {
        id: chapter.id,
        title: chapter.title,
        lectures: chapter.lectures.map(lecture => ({
          id: lecture.id,
          name: lecture.name,
          title: lecture.title,
          path: lecture.path,
          file_path: lecture.path, // 添加 file_path 字段供前端使用
          file_type: lecture.file_type,
          file_size: lecture.file_size
        }))
      };

      res.json({
        success: true,
        data: formattedChapter,
        message: '获取章节详情成功'
      });
    } catch (error) {
      logger.error('获取章节详情失败:', error);
      res.status(500).json({
        success: false,
        message: '获取章节详情失败',
        error: error.message
      });
    }
  }

  // 创建新章节
  static async createChapter(req, res) {
    try {
      const errors = validationResult(req);
      if (!errors.isEmpty()) {
        return res.status(400).json({
          success: false,
          message: '输入数据验证失败',
          errors: errors.array()
        });
      }

      const { id, title, sort_order } = req.body;
      
      // 检查章节ID是否已存在
      const existingChapter = await Chapter.findByPk(id);
      if (existingChapter) {
        return res.status(400).json({
          success: false,
          message: '章节ID已存在'
        });
      }

      const chapter = await Chapter.createChapter({
        id,
        title,
        sort_order: sort_order || 0
      });

      res.status(201).json({
        success: true,
        data: chapter,
        message: '创建章节成功'
      });
    } catch (error) {
      logger.error('创建章节失败:', error);
      res.status(500).json({
        success: false,
        message: '创建章节失败',
        error: error.message
      });
    }
  }

  // 更新章节
  static async updateChapter(req, res) {
    try {
      const errors = validationResult(req);
      if (!errors.isEmpty()) {
        return res.status(400).json({
          success: false,
          message: '输入数据验证失败',
          errors: errors.array()
        });
      }

      const { chapterId } = req.params;
      const { title, sort_order, status } = req.body;

      const updatedRows = await Chapter.updateChapter(chapterId, {
        title,
        sort_order,
        status
      });

      if (updatedRows === 0) {
        return res.status(404).json({
          success: false,
          message: '章节不存在'
        });
      }

      res.json({
        success: true,
        message: '更新章节成功'
      });
    } catch (error) {
      logger.error('更新章节失败:', error);
      res.status(500).json({
        success: false,
        message: '更新章节失败',
        error: error.message
      });
    }
  }

  // 删除章节
  static async deleteChapter(req, res) {
    try {
      const { chapterId } = req.params;
      
      const updatedRows = await Chapter.deleteChapter(chapterId);
      
      if (updatedRows === 0) {
        return res.status(404).json({
          success: false,
          message: '章节不存在'
        });
      }

      res.json({
        success: true,
        message: '删除章节成功'
      });
    } catch (error) {
      logger.error('删除章节失败:', error);
      res.status(500).json({
        success: false,
        message: '删除章节失败',
        error: error.message
      });
    }
  }

  // 获取所有讲义
  static async getAllLectures(req, res) {
    try {
      const { chapter_id, file_type, search } = req.query;
      let lectures;

      if (search) {
        lectures = await Lecture.search(search);
      } else if (chapter_id) {
        lectures = await Lecture.getByChapterId(chapter_id);
      } else if (file_type) {
        lectures = await Lecture.getByFileType(file_type);
      } else {
        lectures = await Lecture.getAll();
      }

      res.json({
        success: true,
        data: lectures,
        message: '获取讲义列表成功'
      });
    } catch (error) {
      logger.error('获取讲义列表失败:', error);
      res.status(500).json({
        success: false,
        message: '获取讲义列表失败',
        error: error.message
      });
    }
  }

  // 获取特定讲义
  static async getLecture(req, res) {
    try {
      const { lectureId } = req.params;
      const lecture = await Lecture.getById(lectureId);
      
      if (!lecture) {
        return res.status(404).json({
          success: false,
          message: '讲义不存在'
        });
      }

      res.json({
        success: true,
        data: lecture,
        message: '获取讲义详情成功'
      });
    } catch (error) {
      logger.error('获取讲义详情失败:', error);
      res.status(500).json({
        success: false,
        message: '获取讲义详情失败',
        error: error.message
      });
    }
  }

  // 创建新讲义
  static async createLecture(req, res) {
    try {
      const errors = validationResult(req);
      if (!errors.isEmpty()) {
        return res.status(400).json({
          success: false,
          message: '输入数据验证失败',
          errors: errors.array()
        });
      }

      const { chapter_id, name, title, path, file_type, file_size, sort_order } = req.body;
      
      // 检查章节是否存在
      const chapter = await Chapter.findByPk(chapter_id);
      if (!chapter) {
        return res.status(400).json({
          success: false,
          message: '指定的章节不存在'
        });
      }

      const lecture = await Lecture.createLecture({
        chapter_id,
        name,
        title,
        path,
        file_type,
        file_size: file_size || 0,
        sort_order: sort_order || 0
      });

      res.status(201).json({
        success: true,
        data: lecture,
        message: '创建讲义成功'
      });
    } catch (error) {
      logger.error('创建讲义失败:', error);
      res.status(500).json({
        success: false,
        message: '创建讲义失败',
        error: error.message
      });
    }
  }

  // 更新讲义
  static async updateLecture(req, res) {
    try {
      const errors = validationResult(req);
      if (!errors.isEmpty()) {
        return res.status(400).json({
          success: false,
          message: '输入数据验证失败',
          errors: errors.array()
        });
      }

      const { lectureId } = req.params;
      const { chapter_id, name, title, path, file_type, file_size, sort_order, status } = req.body;

      // 如果更新了章节ID，检查新章节是否存在
      if (chapter_id) {
        const chapter = await Chapter.findByPk(chapter_id);
        if (!chapter) {
          return res.status(400).json({
            success: false,
            message: '指定的章节不存在'
          });
        }
      }

      const updatedRows = await Lecture.updateLecture(lectureId, {
        chapter_id,
        name,
        title,
        path,
        file_type,
        file_size,
        sort_order,
        status
      });

      if (updatedRows === 0) {
        return res.status(404).json({
          success: false,
          message: '讲义不存在'
        });
      }

      res.json({
        success: true,
        message: '更新讲义成功'
      });
    } catch (error) {
      logger.error('更新讲义失败:', error);
      res.status(500).json({
        success: false,
        message: '更新讲义失败',
        error: error.message
      });
    }
  }

  // 删除讲义
  static async deleteLecture(req, res) {
    try {
      const { lectureId } = req.params;
      
      const updatedRows = await Lecture.deleteLecture(lectureId);
      
      if (updatedRows === 0) {
        return res.status(404).json({
          success: false,
          message: '讲义不存在'
        });
      }

      res.json({
        success: true,
        message: '删除讲义成功'
      });
    } catch (error) {
      logger.error('删除讲义失败:', error);
      res.status(500).json({
        success: false,
        message: '删除讲义失败',
        error: error.message
      });
    }
  }

  // 批量更新讲义排序
  static async updateLectureOrder(req, res) {
    try {
      const { lectureIds } = req.body;
      
      if (!Array.isArray(lectureIds) || lectureIds.length === 0) {
        return res.status(400).json({
          success: false,
          message: '请提供有效的讲义ID数组'
        });
      }

      await Lecture.updateSortOrder(lectureIds);

      res.json({
        success: true,
        message: '更新讲义排序成功'
      });
    } catch (error) {
      logger.error('更新讲义排序失败:', error);
      res.status(500).json({
        success: false,
        message: '更新讲义排序失败',
        error: error.message
      });
    }
  }

  // 获取统计信息
  static async getStats(req, res) {
    try {
      const chapterStats = await Chapter.getStats();
      const lectureStats = await Lecture.getStats();

      res.json({
        success: true,
        data: {
          chapters: chapterStats,
          lectures: lectureStats
        },
        message: '获取统计信息成功'
      });
    } catch (error) {
      logger.error('获取统计信息失败:', error);
      res.status(500).json({
        success: false,
        message: '获取统计信息失败',
        error: error.message
      });
    }
  }
}

module.exports = LectureController;